<template>
    <el-drawer v-model="isShow" size="50%" :destroy-on-close="true" @close="closeHandle" :close-on-press-escape="false"
        :close-on-click-modal="false" :show-close="false">
        <template #header="{ close, titleId, titleClass }">
            <h4 :id="titleId" :class="titleClass">{{ title }}</h4>
        </template>
        <el-form :model="form" ref="formRef" :rules="rules" v-loading="loading">
            <el-row class="mb-4">
                <el-col class="tittle">
                    <div class="tittle_dian"></div><span>申请部门信息</span>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12" class="mb-3">
                    <el-form-item label="选择单位" required label-width="100px" prop="policeAreaUnitId">
                        <el-cascader v-model="form.policeAreaUnitId" :options="UnitOptions" @change="handleChange"
                            :props="{ value: 'deptId', label: 'deptName', children: 'children', checkStrictly: true, emitPath: false, expandTrigger: 'click' }"
                            :show-all-levels="false" :disabled="isApprove" style="width:100%" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-3">
                    <el-form-item label="选择办案区" required label-width="100px" prop="policeareaId">
                        <el-select v-model="form.policeareaId" :disabled="isApprove" @change="policeareaIdChange">
                            <el-option v-for="item in PoliceOptions" :key="item.policeareaId" :label="item.areaname"
                                :value="item.policeareaId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-3">
                    <el-form-item label="办案部门" required label-width="100px">
                        <el-select v-model="form.depId" :disabled="true">
                            <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName"
                                :value="item.deptId" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-3">
                    <el-form-item label="承办人" required label-width="100px">
                        <el-select v-model="form.askerId" :disabled="true">
                            <el-option v-for="item in PeopleOptions" :key="item.userId" :label="item.userName"
                                :value="item.userId" />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="使用时间" required label-width="100px" prop="startdate">
                        <el-date-picker :disabled="isApprove" v-model="form.startdate" type="datetime"
                            placeholder="请选择日期" value-format="YYYY-MM-DD HH:mm:ss" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-3">
                    <el-form-item label="离开时间" label-width="100px">
                        <el-date-picker :disabled="isApprove" v-model="form.enddate" type="datetime" placeholder="请选择日期"
                            value-format="YYYY-MM-DD HH:mm:ss" />
                    </el-form-item>
                </el-col>
                <el-col :span="24" class="mb-3">
                    <el-row :gutter="20">
                        <el-col :span="12" class="mb-3">
                            <el-form-item label="使用明细" label-width="100px" required prop="roomdetail">
                                <el-input type="textarea" :rows="3" resize="none" placeholder="请输入用房名称及数量"
                                    v-if="form.roomdetail !== null" v-model="form.roomdetail" clearable
                                    :disabled="isApprove" />
                                <el-input v-else type="textarea" :rows="3" resize="none" v-model="form.roomdetail"
                                    clearable :disabled="isApprove" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12" class="mb-3">
                            <el-form-item label="选择房间类型" label-width="100px">
                                <el-select v-model="roomdetail2" @change="changeroomdetail">
                                    <el-option v-for="item in roomTypeList" :key="item.value" :label="item.label"
                                        :value="item.value" />
                                </el-select>
                            </el-form-item>
                            
                        </el-col>
                        <!-- <el-col :span="12" class="mb-3">
                            <el-button type="primary" @click="putmessage('询问室')" v-if="isshowputmessageBtn">询问室</el-button>
                            <el-button type="primary" @click="putmessage('讯问室')" v-if="isshowputmessageBtn">讯问室</el-button>
                        </el-col> -->
                    </el-row>
                </el-col>
            </el-row>
            <el-row class="mt-4 mb-3">
                <el-col class="tittle">
                    <div class="tittle_dian"></div><span>案件/涉案人情况</span>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24" class="mb-3">
                    <el-button type="primary" v-if="isshowBtn"
                        @click="AddEditjwApplydetailListRef.showAddjwApplydetailList(form, 'add')">
                        <el-icon class="me-2">
                            <Plus />
                        </el-icon>新增
                    </el-button>
                </el-col>
                <el-col :span="24" class="">
                    <el-table :data="form.jwApplydetailList"
                    @row-dblclick="handleRowDblClick"
                    stripe 
                    border
                    :row-style="tableRowStyle"
                    >
                        <el-table-column label="案件名称" prop="caseName" />
                        <el-table-column label="涉案人" prop="userName" />
                        <el-table-column label="涉案人身份" align="center" prop="userType">
                            <template #default="scope">
                                <dict-tag :options="nj_sheanren_type" :value="scope.row.userType" />
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" width="190" align="center">
                            <template #default="scope">
                                <template ref="" v-if="isshowBtn">
                                    <el-button link size="small" type="primary"
                                        @click="AddEditjwApplydetailListRef.showEditjwApplydetailList(scope.row, scope.$index, '修改案件信息', 'addEdit')">
                                        <el-icon class="me-1">
                                            <Edit />
                                        </el-icon>
                                        编辑
                                    </el-button>
                                    <el-button link size="small" type="primary"
                                        @click="AddEditjwApplydetailListRef.showEditjwApplydetailList(scope.row, scope.$index, '查看案件信息', 'See')">
                                        <el-icon class="me-1">
                                            <Edit />
                                        </el-icon>
                                        详情
                                    </el-button>
                                    <el-button link size="small" type="danger"
                                        @click="removejwApplydetailInfo(scope.row)">
                                        <el-icon class="me-1">
                                            <Delete />
                                        </el-icon>
                                        移除
                                    </el-button>
                                </template>
                                <template v-else>
                                    <el-button link size="small" type="primary"
                                        @click="AddEditjwApplydetailListRef.showEditjwApplydetailList(scope.row, scope.$index, '修改案件信息', 'isApprove')">
                                        <el-icon class="me-1">
                                            <Edit />
                                        </el-icon>
                                        查看
                                    </el-button>
                                </template>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
            <el-row class="mt-4 mb-3">
                <el-col class="tittle">
                    <div class="tittle_dian"></div><span>承办审批意见</span>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12" class="mb-3">
                    <el-form-item label="承办人申请意见" label-width="140px">
                        <el-input v-model="form.askdetail" :disabled="isApprove" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-3">
                    <el-form-item label="办案部门审批意见" required label-width="140px" prop="approvaldetail">
                        <el-input v-model="form.approvaldetail" :disabled="isApprove" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <template v-if="fjApproveMsg">
                    <el-col :span="12" class="mb-3">
                        <el-form-item label="法警部门审核内容" required label-width="140px" prop="fjdetail">
                            <el-input v-model="form.fjdetail" :disabled="isfjApproveMsg" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="mb-3">
                        <el-form-item label="审核时间" label-width="140px">
                            <el-input v-model="form.fjdate" :disabled="true" />
                        </el-form-item>
                    </el-col>
                </template>
            </el-row>
            <el-row :gutter="20">
                <template v-if="LeaderApproveBtn || LeaderApproveMsg">
                    <el-col :span="12" class="mb-3">
                        <el-form-item label="分管领导审核内容" required label-width="140px" prop="leaderdetail">
                            <el-input v-model="form.leaderdetail" :disabled="isLeaderApproveMsg" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" class="mb-3">
                        <el-form-item label="审核时间" label-width="140px">
                            <el-input v-model="form.leaderdate" :disabled="true" />
                        </el-form-item>
                    </el-col>

                </template>
            </el-row>
        </el-form>
        <template #footer>
            <template v-if="fjApproveBtn">
                <el-button type="primary" @click="BAApplyFjConfirmBtn">确定实施</el-button>
                <el-button type="primary" @click="BAApplyforLeaderBtn">提交分管领导</el-button>
                <el-button type="primary" @click="BAApplycancelBtn">回退</el-button>
            </template>
            <template v-if="LeaderApproveBtn">
                <el-button type="primary" @click="leaderConfirmBtn">确定</el-button>
                <el-button type="primary" @click="cancelLeaderBtn">回退</el-button>
            </template>
            <template v-if="AddisshowBtn">
                <el-button type="primary" @click="submitHandle">确定</el-button>
            </template>
            <el-button @click="isShow = false" style="margin-left:20px">关闭</el-button>
        </template>
    </el-drawer>
    <AddEditjwApplydetailList ref="AddEditjwApplydetailListRef" @ByinquestList="ByinquestLists" />
</template>

<script setup>
import { getCurrentInstance } from "vue";

import { getUserProfile } from "@/api/system/user";
import { listDept, listDeptAll } from "@/api/system/dept";
import { getPoliceAreaList, policeAreaTreeList } from "@/api/PoliceAreaManage/PoliceAreaManage";

import {
    createBAApply, editBAApply, getBAApplyInfo, BAApplyFjConfirm, BAApplyforLeader, BAApplycancel, BAApplyapplyCancel,
    BAApplyleaderConfirm, BAApplycancelLeaderConfirm
} from "@/api/BAApply/BAApply";

import AddEditjwApplydetailList from "@/components/AddEditjwApplydetailList/AddEditjwApplydetailList.vue";
import { getRoomList} from "@/api/Room/room";

import {getCurrentTime} from "@/utils/utils.js";
const {proxy} = getCurrentInstance()
const {nj_sheanren_type, nj_anjian_type,nj_anjian_status,nj_policearea_type} =
proxy.useDict('nj_sheanren_type', 'nj_anjian_type', 'nj_anjian_status', 'nj_policearea_type')
// 是否显示抽屉
const roomTypeList = ref([])

const isShow = ref(false)
const loading = ref(false)

const isshowputmessageBtn = ref(true)

const isshowBtn = ref(true)
const AddisshowBtn = ref(true)
const fjApproveBtn = ref(false)
const fjApproveMsg = ref(false)
const isfjApproveMsg = ref(false)

const LeaderApproveMsg = ref(false)
const isLeaderApproveMsg = ref(false)

const LeaderApproveBtn = ref(false)


const isDisabled = ref(false)
const isApprove = ref(false)
const isLeader = ref(false)

const AddEditjwApplydetailListRef = ref({})

// 抽屉标题
const title = ref('')

// 所属部门-人员列表
const PeopleOptions = ref([]);
// 警务区
const policeareaOptions = ref([]);
// 所属部门
const deptOptions = ref([]);
const UnitOptions = ref([]);
const PoliceOptions = ref([]);

const props1 = {
    checkStrictly: true,
}
const formType = ref("");
const isshenpi = ref("");
// 通知事件
const emit = defineEmits(['getBAApplyList'])

const changeShowStatus = () => {
    isShow.value = !isShow.value
}
const rules = {
    policeAreaUnitId: [{ required: true, message: "单位不能为空", trigger: "change" }],
    policeareaId: [{ required: true, message: "办案区不能为空", trigger: "blur" }],
    startdate: [{ required: true, message: "使用时间不能为空", trigger: "blur" }],
    roomdetail: [{ required: true, message: "使用明细不能为空", trigger: "change" }],
    approvaldetail: [{ required: true, message: "办案部门审批意见不能为空", trigger: "blur" }],
    fjdetail: [{ required: true, message: "法警部门审核内容不能为空", trigger: "blur" }],
    leaderdetail: [{ required: true, message: "分管领导审核内容不能为空", trigger: "blur" }],
}
const form = ref({
    jwApplydetailList: [],
    askdetail: '',
    approvaldetail: '',
    fjdetail: '',
    leaderdetail: '',
    actuserId: '1',
    state: '0',
    roomdetail: ''
})

const handleRowDblClick = (row) => {
    console.log(row)
    AddEditjwApplydetailListRef.value.showEditjwApplydetailList(row, '1', '查看案件信息', 'isApprove')
}
onMounted(() => {

})
// 斑马纹样式函数
const tableRowStyle = ({ row, rowIndex }) => {
    if (rowIndex % 2 === 0) {
        return { backgroundColor: '#e6ecff' }; // 偶数行背景色
    }
    return {}; // 奇数行默认透明
}
const roomdetail2 = ref()
const changeroomdetail = async () => {
    console.log(roomdetail2.value)
    form.value.roomdetail = roomdetail2.value
}
const getRoomLists = async () => {
    var RoomListqueryParams = {
        policeareaId:form.value.policeareaId
    }
    getRoomList(RoomListqueryParams).then(res => {
        // 提取 roomtypeId 并去重
            const uniqueRoomTypes = new Set(res.rows.map(item => item.roomtypeId));
        // 转换为 { value: 'xxx', label: 'xxx' } 的格式
        
        roomTypeList.value = Array.from(uniqueRoomTypes).map(type => ({
            value: type,
            label: type,
        }));
        // 过滤掉 value 为 "法警值班室" 的项
        roomTypeList.value = roomTypeList.value.filter(item => item.value !== "法警值班室");
        console.log(roomTypeList.value)
        })
}

const findLabelById = (data, id) => {
    for (const item of data) {
        if (item.id === id) {
            return item.label;
        }
        if (item.children) {
            const found = findLabelById(item.children, id);
            if (found) {
                return found;
            }
        }
    }
    return null; // 如果未找到，返回 null
};
const lastValue = computed(() => form.value.policeareaId?.slice(-1)[0] || ''); // 获取最后一个值
const handleChange = (node) => {
    form.value.policeareaId = ''
    // const selectedLabel = findLabelByValue(UnitOptions.value, node);
    // form.value.unitname = selectedLabel
    const querydata = {
        unitId: node,
        areatype: form.value.type
    }
    getPoliceAreaList(querydata).then(res => {
        PoliceOptions.value = res.rows
    })
};
const policeareaIdChange = (value) => {
    form.value.policeareaId = value
    const selectedOption = PoliceOptions.value.find(item => item.policeareaId === value);
    form.value.policeareaname = selectedOption.areaname
    form.value.roomdetail = ''
    roomdetail2.value = ''
    roomTypeList.value = []
    getRoomLists()
};
// 工具函数递归查找 label
function findLabelByValue(options, value) {
    for (const option of options) {
        if (option.deptId === value) {
            return option.deptName;
        }
        if (option.children) {
            const label = findLabelByValue(option.children, value);
            if (label) {
                return label;
            }
        }
    }
    return null;
}
// 获取部门-根据单位ID筛选出当前单位的部门
const getDepartment = async (unitId) => {
    const deptqueryParams = {}
    await listDeptAll(deptqueryParams).then(res => {
        deptOptions.value = proxy.handleTree(
            res.data.filter(item => !item.isUnit && item.parentId == unitId),
            "deptId"
        );
        UnitOptions.value = proxy.handleTree(
            res.data.filter(item => item.isUnit),
            "deptId"
        );
    })
}
// 根据单位ID获取对应办案区列表
const getPoliceAreaLists = async (unitId, areaType) => {
    const querydata = {
        unitId: unitId,
        areatype: areaType
    }
    await getPoliceAreaList(querydata).then(res => {
        // 处理数据并输出
        PoliceOptions.value = res.rows
    })
}

const showAddBAApply = async (tittleV, formTypeV, ApplyTypeV) => {
    title.value = tittleV;
    loading.value = false
    isApprove.value = false
    fjApproveMsg.value = false
    LeaderApproveMsg.value = false
    isshowputmessageBtn.value = true
    form.value.askdetail = form.value.askdetail || '同意';
    form.value.approvaldetail = form.value.approvaldetail || '同意';
    changeShowStatus();
    if (formTypeV == "add") {
        isshowBtn.value = true
        AddisshowBtn.value = true
    }
    try {
        // const res = await getUserProfile();
        getUserProfile().then(res => {
            PeopleOptions.value = [{
                userId: res.data.userId,
                userName: res.data.userName
            }]
            form.value = {
                ...form.value,
                type: ApplyTypeV,        //1的时候为办案中心使用申请，2自侦办案去，3指定居所
                adduserId: res.data.adduserId,
                depId: res.data.deptId,
                depname: res.data.deptName,
                askerId: res.data.userId,
                policeAreaUnitId: res.data.unitId
            }
            getDepartment(res.data.unitId);
            getPoliceAreaLists(res.data.unitId, ApplyTypeV);
        })
    } catch (error) {
        console.error(error);
    }
}

const showEditBAApply = async (data, tittleV, formTypeV, areaTypeV) => {
    title.value = tittleV
    changeShowStatus()

    loading.value = true
    await getDepartment(data.unit_id);
    await getBAApplyInfo(data.jw_apply_id).then(res => {
        form.value = res.data
        form.value.depId = Number(res.data.depId)
        form.value.policeAreaUnitId = Number(res.data.policeAreaUnitId)
        form.value.askerId = Number(res.data.askerId)
        PeopleOptions.value = [{
            userId: res.data.askerId,
            userName: res.data.askerName
        }]
        deptOptions.value = [{
            deptName: res.data.depname,
            deptId: res.data.depId
        }]
        loading.value = false
    })
    await getPoliceAreaLists(form.value.policeAreaUnitId, areaTypeV);
    if (formTypeV == 'Edit') {
        isshowBtn.value = true
        isApprove.value = false
        AddisshowBtn.value = true
        fjApproveMsg.value = false
        LeaderApproveMsg.value = false
        isshowputmessageBtn.value = true
    }
    if (formTypeV == 'See') {
        console.log(isshowBtn.value, 'isshowBtn.value')
        isshowBtn.value = false
        console.log(isshowBtn.value, 'isshowBtn.value')
        AddisshowBtn.value = false
        isshowputmessageBtn.value = false
        isApprove.value = true
        fjApproveMsg.value = true
        isfjApproveMsg.value = true

        isfjApproveMsg.value = true
        LeaderApproveMsg.value = true
        isLeaderApproveMsg.value = true

        fjApproveBtn.value = false
        LeaderApproveBtn.value = false
    }
    if (formTypeV == 'fjApprove') {

        fjApproveBtn.value = true
        fjApproveMsg.value = true
        isfjApproveMsg.value = false
        LeaderApproveMsg.value = false
        isshowputmessageBtn.value = false
        AddisshowBtn.value = false
        isshowBtn.value = false

        isApprove.value = true
        form.value.fjdetail = form.value.fjdetail || '同意';
        const time = getCurrentTime()
        form.value.fjdate = form.value.fjdate || time
    }
    if (formTypeV == 'LeaderApprove') {
        isshowBtn.value = false
        fjApproveBtn.value = false
        fjApproveMsg.value = true
        isshowputmessageBtn.value = false
        isfjApproveMsg.value = true
        isLeaderApproveMsg.value = false

        LeaderApproveBtn.value = true
        AddisshowBtn.value = false
        isApprove.value = true
        form.value.leaderdetail = form.value.leaderdetail || '同意';
        const time = getCurrentTime()
        form.value.leaderdate = form.value.leaderdate || time
    }
}
defineExpose({ showAddBAApply, showEditBAApply })

const submitHandle = async () => {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            console.log(form.value)
            // return false
            if (form.value.jwApplydetailList.length == 0) {
                proxy.$modal.msgWarning(`涉案人员不能为空`)
                return false
            }
            loading.value = true
            if (form.value['jwApplyId']) {
                editBAApply(form.value).then(res => {
                    loading.value = false
                    changeShowStatus()
                    emit('getBAApplyList', '编辑')
                })
            } else {
                createBAApply(form.value).then(res => {
                    loading.value = false
                    changeShowStatus()
                    emit('getBAApplyList', '新增一个')
                })
            }
        }
    });
}
const BAApplyFjConfirmBtn = async () => {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            const data = {
                fjdetail: form.value.fjdetail,
                jwApplyId: form.value.jwApplyId
            }
            BAApplyFjConfirm(data).then(res => {
                changeShowStatus()
                emit('getBAApplyList', '提交分管领导')
            })
        }
    });

}
const BAApplyforLeaderBtn = async () => {
    const data = {
        fjdetail: form.value.fjdetail,
        jwApplyId: form.value.jwApplyId
    }
    await BAApplyforLeader(data).then(res => {
        changeShowStatus()
        emit('getBAApplyList', '提交分管领导')
    })
}
const BAApplycancelBtn = async () => {
    const data = {
        fjdetail: form.value.fjdetail,
        jwApplyId: form.value.jwApplyId
    }
    await BAApplycancel(data).then(res => {
        changeShowStatus()
        emit('getBAApplyList', '法警负责人-回退')
    })
}
const BAApplyapplyCancelBtn = async () => {
    const data = {
        fjdetail: form.value.fjdetail,
        jwApplyId: form.value.jwApplyId
    }
    await BAApplyapplyCancel(data).then(res => {
        changeShowStatus()
        emit('getBAApplyList', '法警负责人-取消')
    })
}
const leaderConfirmBtn = async () => {
    proxy.$refs["formRef"].validate(valid => {
        if (valid) {
            const data = {
                fjdetail: form.value.fjdetail,
                jwApplyId: form.value.jwApplyId
            }
            BAApplyleaderConfirm(data).then(res => {
                changeShowStatus()
                emit('getBAApplyList', '分管领导确认')
            })
        }
    });

}
const cancelLeaderBtn = async () => {
    const data = {
        fjdetail: form.value.fjdetail,
        jwApplyId: form.value.jwApplyId
    }
    await BAApplycancelLeaderConfirm(data).then(res => {
        changeShowStatus()
        emit('getBAApplyList', '分管领导-回退')
    })
}


const removejwApplydetailInfo = (row) => {
    const index = form.value.jwApplydetailList.indexOf(row);
    if (index !== -1) {
        form.value.jwApplydetailList.splice(index, 1);
    }
}
const ByinquestLists = (data, index) => {
    if (index == null || index == undefined) {
        // 更新对应 index 的数据
        form.value.jwApplydetailList.push(data);
    } else {
        // 添加新数据
        form.value.jwApplydetailList[index] = data;
    }
}
// 快捷输入

const putmessage = (message) => {
    console.log(form.value.roomdetail)
    console.log(message)
    form.value.roomdetail += message;
    // form.value.roomdetail = message
}
// 关闭后的回调事件
const closeHandle = () => {
    form.value = {
        jwApplydetailList: [],
        roomdetail: ''
    }
    console.log(123123)
}
</script>

<style lang="scss" scoped>
/* 保留斑马纹的同时添加悬停效果 */
:deep().el-table--striped .el-table__body tr.el-table__row--striped:hover td {
  background-color: #a5b8f4; /* 悬停时的红色 */
}

:deep().el-table__body tr:hover td {
  background-color: #a5b8f4; /* 悬停时的红色 */
}
h4 {
    margin: 10px 0;
}

:deep() .el-input {
    width: 100%;
}

:deep().el-input__wrapper {
    width: 100%;
}

:deep().el-select__wrapper {
    width: 100%;
}

.el-form-item {
    margin-bottom: 0;
}

.tittle {
    display: flex;
    display: inline-flex;
    align-items: center;
    color: #0077B9;
}

.tittle_dian {
    width: 5px;
    height: 16px;
    margin-right: 10px;
    background: #0077B9;
}

</style>